#! /bin/sh

### BEGIN INIT INFO
# Provides:          firstrun
# Required-Start:    $remote_fs
# Required-Stop:
# Should-Start:
# Default-Start:     S
# Default-Stop:
# Short-Description: Script to run when cubian first starting
# Description:       Something needs to be done when cubian is
#                    starting at first time.
#                      
#                    1. regenerate ssh host key
#                    2. regenerate ajenti private key
### END INIT INFO

N=/etc/init.d/firstrun

set -e

do_expand_rootfs(){
    device="/dev/mmcblk0"
    (echo d; echo n; echo p; echo 1; echo ; echo; echo w;) | fdisk $device 
	return 0
}

case "$1" in
  start)
		echo "Expanding rootfs..." >> /dev/tty0
		if [ -f /flag ]; then
			rm /flag
			/sbin/insserv -r firstrun
			echo "Second run. This process takes around 1 minute to finish..." >> /dev/tty0
			/sbin/resize2fs /dev/mmcblk0p1
			echo "Update packages list..."
			apt-get update >/dev/null 2>&1
			echo "Add PermitRootLogin" >> /dev/tty0
			sed -e 's/PermitRootLogin without-password/PermitRootLogin yes/g' -i /etc/ssh/sshd_config
			service ssh restart
			echo "Creating ssh keys..." >> /dev/tty0
	        rm /etc/ssh/ssh_host*
            dpkg-reconfigure openssh-server
		else
			echo "First run. This process takes around 1 minute to finish..." >> /dev/tty0
			if do_expand_rootfs; then
				echo "Expanding rootfs success, rebooting automatically..." >> /dev/tty0
				touch /flag
				/sbin/reboot
			else
				echo "Expanding rootfs has failed, see log files." 
			fi
		fi
        ;;
  *)
        echo "Usage: $N {start}" >&2
        exit 1
        ;;
esac
exit 0